package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;

import com.cyy.springbootinit.model.dto.dorimitoryexpensebill.DormitoryExpenseBillAddRequest;
import com.cyy.springbootinit.model.dto.dorimitoryexpensebill.DormitoryExpenseBillEditRequest;
import com.cyy.springbootinit.model.dto.dorimitoryexpensebill.DormitoryExpenseBillQueryRequest;
import com.cyy.springbootinit.model.dto.dorimitoryexpensebill.DormitoryExpenseBillUpdateRequest;
import com.cyy.springbootinit.model.entity.DormitoryExpenseBill;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.DormitoryExpenseBillVO;
import com.cyy.springbootinit.service.DormitoryExpenseBillService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 宿舍水电支出接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/dormitoryExpenseBill")
@Slf4j
public class DormitoryExpenseBillController {

    @Resource
    private DormitoryExpenseBillService dormitoryExpenseBillService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建宿舍水电支出
     *
     * @param dormitoryExpenseBillAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addDormitoryExpenseBill(@RequestBody DormitoryExpenseBillAddRequest dormitoryExpenseBillAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(dormitoryExpenseBillAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        DormitoryExpenseBill dormitoryExpenseBill = new DormitoryExpenseBill();
        BeanUtils.copyProperties(dormitoryExpenseBillAddRequest, dormitoryExpenseBill);
        // 数据校验
        dormitoryExpenseBillService.validDormitoryExpenseBill(dormitoryExpenseBill, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        // 写入数据库
        boolean result = dormitoryExpenseBillService.save(dormitoryExpenseBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newDormitoryExpenseBillId = dormitoryExpenseBill.getBillId();
        return ResultUtils.success(newDormitoryExpenseBillId);
    }

    /**
     * 删除宿舍水电支出
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteDormitoryExpenseBill(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        DormitoryExpenseBill oldDormitoryExpenseBill = dormitoryExpenseBillService.getById(id);
        ThrowUtils.throwIf(oldDormitoryExpenseBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if ( !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = dormitoryExpenseBillService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新宿舍水电支出（仅管理员可用）
     *
     * @param dormitoryExpenseBillUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateDormitoryExpenseBill(@RequestBody DormitoryExpenseBillUpdateRequest dormitoryExpenseBillUpdateRequest) {
        if (dormitoryExpenseBillUpdateRequest == null || dormitoryExpenseBillUpdateRequest.getBillId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DormitoryExpenseBill dormitoryExpenseBill = new DormitoryExpenseBill();
        BeanUtils.copyProperties(dormitoryExpenseBillUpdateRequest, dormitoryExpenseBill);
        // 数据校验
        dormitoryExpenseBillService.validDormitoryExpenseBill(dormitoryExpenseBill, false);
        // 判断是否存在
        long id = dormitoryExpenseBillUpdateRequest.getBillId();
        DormitoryExpenseBill oldDormitoryExpenseBill = dormitoryExpenseBillService.getById(id);
        ThrowUtils.throwIf(oldDormitoryExpenseBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = dormitoryExpenseBillService.updateById(dormitoryExpenseBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取宿舍水电支出（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<DormitoryExpenseBillVO> getDormitoryExpenseBillVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        DormitoryExpenseBill dormitoryExpenseBill = dormitoryExpenseBillService.getById(id);
        ThrowUtils.throwIf(dormitoryExpenseBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(dormitoryExpenseBillService.getDormitoryExpenseBillVO(dormitoryExpenseBill, request));
    }

    /**
     * 分页获取宿舍水电支出列表（仅管理员可用）
     *
     * @param dormitoryExpenseBillQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<DormitoryExpenseBill>> listDormitoryExpenseBillByPage(@RequestBody DormitoryExpenseBillQueryRequest dormitoryExpenseBillQueryRequest) {
        long current = dormitoryExpenseBillQueryRequest.getCurrent();
        long size = dormitoryExpenseBillQueryRequest.getPageSize();
        // 查询数据库
        Page<DormitoryExpenseBill> dormitoryExpenseBillPage = dormitoryExpenseBillService.page(new Page<>(current, size),
                dormitoryExpenseBillService.getQueryWrapper(dormitoryExpenseBillQueryRequest));
        return ResultUtils.success(dormitoryExpenseBillPage);
    }

    /**
     * 分页获取宿舍水电支出列表（封装类）
     *
     * @param dormitoryExpenseBillQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<DormitoryExpenseBillVO>> listDormitoryExpenseBillVOByPage(@RequestBody DormitoryExpenseBillQueryRequest dormitoryExpenseBillQueryRequest,
                                                               HttpServletRequest request) {
        long current = dormitoryExpenseBillQueryRequest.getCurrent();
        long size = dormitoryExpenseBillQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<DormitoryExpenseBill> dormitoryExpenseBillPage = dormitoryExpenseBillService.page(new Page<>(current, size),
                dormitoryExpenseBillService.getQueryWrapper(dormitoryExpenseBillQueryRequest));
        // 获取封装类
        return ResultUtils.success(dormitoryExpenseBillService.getDormitoryExpenseBillVOPage(dormitoryExpenseBillPage, request));
    }

    /**
     * 分页获取当前登录用户创建的宿舍水电支出列表
     *
     * @param dormitoryExpenseBillQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<DormitoryExpenseBillVO>> listMyDormitoryExpenseBillVOByPage(@RequestBody DormitoryExpenseBillQueryRequest dormitoryExpenseBillQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(dormitoryExpenseBillQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        long current = dormitoryExpenseBillQueryRequest.getCurrent();
        long size = dormitoryExpenseBillQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<DormitoryExpenseBill> dormitoryExpenseBillPage = dormitoryExpenseBillService.page(new Page<>(current, size),
                dormitoryExpenseBillService.getQueryWrapper(dormitoryExpenseBillQueryRequest));
        // 获取封装类
        return ResultUtils.success(dormitoryExpenseBillService.getDormitoryExpenseBillVOPage(dormitoryExpenseBillPage, request));
    }

    /**
     * 编辑宿舍水电支出（给用户使用）
     *
     * @param dormitoryExpenseBillEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editDormitoryExpenseBill(@RequestBody DormitoryExpenseBillEditRequest dormitoryExpenseBillEditRequest, HttpServletRequest request) {
        if (dormitoryExpenseBillEditRequest == null || dormitoryExpenseBillEditRequest.getBillId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DormitoryExpenseBill dormitoryExpenseBill = new DormitoryExpenseBill();
        BeanUtils.copyProperties(dormitoryExpenseBillEditRequest, dormitoryExpenseBill);
        // 数据校验
        dormitoryExpenseBillService.validDormitoryExpenseBill(dormitoryExpenseBill, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = dormitoryExpenseBillEditRequest.getBillId();
        DormitoryExpenseBill oldDormitoryExpenseBill = dormitoryExpenseBillService.getById(id);
        ThrowUtils.throwIf(oldDormitoryExpenseBill == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if ( !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = dormitoryExpenseBillService.updateById(dormitoryExpenseBill);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @GetMapping("/getRecentBill")
    public BaseResponse<List<DormitoryExpenseBill>> getRecentBill( HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        Integer dormitoryId = user.getDormitoryId();
        return ResultUtils.success(dormitoryExpenseBillService.getRecentBill(dormitoryId));
    }
    // endregion
}
